package com.ww.hegou.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ww.hegou.util.IOkHttp;
import com.ww.hegou.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class MoraService {
    @Autowired
    OkHttpUtil okHttpUtil;
    @Value("${quartzService.dd.sync}")
    int port;

    private String getDownloadUrl(String number) throws IOException {
        String url = "https://mora.jp/listenDownload?materialNo=" + number;
        JSONObject jsonObject = JSON.parseObject(get(url).body().string());
        return jsonObject.getString("listenUrl");
    }



    private Response get(String url) throws IOException {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port));
        //1. 创建OkhttpClient 对象
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS)
                .proxy(proxy)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        return client.newCall(request).execute();
    }

    private Response get2(String url) throws IOException {
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1091));
        //1. 创建OkhttpClient 对象
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        return client.newCall(request).execute();
    }

    public Map<String, Object> getMoraInfo(String url, HttpServletResponse res) throws IOException {

        Response response = get(url);
        String body = response.body().string();
        String pattern = "var artistNo=\"\\d+\"";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(body);
        String number = "";
        if (m.find()) {
            log.info("艺人编号:" + m.group(0));
            number = m.group(0);
        }
        String pattern2 = "\\d+";
        Pattern r2 = Pattern.compile(pattern2);
        Matcher m2 = r2.matcher(number);
        String artistNo = "";
        if (m2.find()) {
            artistNo = m2.group(0);
            log.info("艺人编号:2" + artistNo);
        }

        pattern = "var materialNo=\"\\d+\"";
        r = Pattern.compile(pattern);
        m = r.matcher(body);
        if (m.find()) {
            log.info("专辑编号:" + m.group(0));
            number = m.group(0);
        }

        pattern = "\\d+";
        r = Pattern.compile(pattern);
        m = r.matcher(number);
        String materialNo = "";
        if (m.find()) {
            log.info("专辑编号2:" + m.group(0));
            materialNo = m.group(0);
        }
        log.info("艺人编号:{},专辑编号：{}", artistNo, materialNo);
        return getArtistInfo(artistNo, materialNo, res);


    }

    private Map<String, Object> getArtistInfo(String id, String materialNo, HttpServletResponse res) throws IOException {
        Response response = get("https://mora.jp/artistInfo/" + id);
        String body = response.body().string();
        JSONObject jsonObject = JSON.parseObject(body);
        log.info("获取的专辑信息:{}", jsonObject.toJSONString());
        JSONArray jsonArray = jsonObject.getJSONObject("packageResult").getJSONArray("list");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject j = jsonArray.getJSONObject(i);
            if (j.getString("materialNo").equals(materialNo)) {
                return getTrackList(j.getString("packageUrl"), res);
            }
        }
        return null;
    }


    private Map<String, Object> getTrackList(String url, HttpServletResponse res) throws IOException {
        Response response =get(url + "packageMeta.jsonp");
        String body;
        body = response.body().string();
        body = body.substring(13, body.length() - 2);
        JSONObject jsonObject = JSON.parseObject(body);
        log.info(jsonObject.toJSONString());
        JSONArray jsonArray = jsonObject.getJSONArray("trackList");
        int length = jsonArray.size();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list =new ArrayList<>();
        int totaltime = 0;
        for (int i = 0; i < length; i++) {
            JSONObject track = jsonArray.getJSONObject(i);
            String downloadUrl = getDownloadUrl(track.getString("materialNo"));
            String title = track.getString("title");
            Map<String, Object> t   = new HashMap<>();
            t.put("title",title);
            t.put("downloadUrl",downloadUrl);
            t.put("duration",track.getString("duration"));
            list.add(t);
            totaltime+=track.getInteger("duration");
        }

        map.put("trackList",list);
        map.put("totaltime",totaltime);
        map.put("size",list.size());
        map.put("title",jsonObject.getString("title"));
        map.put("samplingFreq",jsonObject.getString("samplingFreq"));
        map.put("price",jsonObject.getString("price"));
        map.put("startDdate",jsonObject.getString("startDate"));
        map.put("bitPerSample",jsonObject.getString("bitPerSample"));
        map.put("packageComment",jsonObject.getString("packageComment"));
        map.put("artistName",jsonObject.getString("artistName"));
        return map;
    }

    public void getZip( HttpServletResponse res,String query) throws IOException {
        Response response =  get2("http://127.0.0.1:5555/music/info?query="+query);
        JSONObject jsonObject =JSON.parseObject(response.body().string());
        JSONArray jsonArray = jsonObject.getJSONArray("trackList");
        int length = jsonArray.size();
        String name = jsonObject.getString("title")+".zip";
        name =  new String(name.getBytes("UTF-8"), "ISO-8859-1");
        res.setHeader("Content-Disposition","attachment;filename="+ name);
        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(res.getOutputStream());
        zous.setUseZip64(Zip64Mode.AsNeeded);
        for (int i = 0; i < length; i++) {
            JSONObject track = jsonArray.getJSONObject(i);
            String title = track.getString("title");
            byte[] bytes= get(track.getString("downloadUrl")).body().bytes();

            ArchiveEntry entry = new ZipArchiveEntry(title+".mp4");
            zous.putArchiveEntry(entry);
            zous.write(bytes);
            zous.closeArchiveEntry();
        }
        zous.close();


    }
}
